package com.sillyhat.project.common.editor;

import com.sillyhat.project.common.constants.ConstantsAttributes;
import org.apache.commons.lang3.time.DateUtils;
import java.beans.PropertyEditorSupport;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * Created by yuxiang on 2017/3/23.
 */
public class DateEditor extends PropertyEditorSupport {
    private boolean emptyAsNull;
    private String dateFormat = "yyyy-MM-dd HH:mm:ss";

    public DateEditor(boolean emptyAsNull) {
        this.emptyAsNull = emptyAsNull;
    }

    public DateEditor(boolean emptyAsNull, String dateFormat) {
        this.emptyAsNull = emptyAsNull;
        this.dateFormat = dateFormat;
    }

    public String getAsText() {
        Date date = (Date) getValue();
        return Objects.isNull(date) ? "":new SimpleDateFormat(this.dateFormat).format(date);
    }

    public void setAsText(String text) {
        if (text == null) {
            setValue(null);
        } else {
            text = text.trim();
            if (this.emptyAsNull && "".equals(text)){
                setValue(null);
            }else
                try {
                    setValue(DateUtils.parseDate(text, ConstantsAttributes.DATE_PATTERNS));
                } catch (Exception e) {
                    setValue(null);
                }
        }
    }
}